import Vue from 'vue'
import Vuex from 'vuex'
import {getRequest} from "../utils/api";
import {putRequest} from "../utils/api";
import SockJS from 'sockjs-client'
import Stomp from 'stompjs'
import {Notification} from 'element-ui'

Vue.use(Vuex)

const now = new Date();

const store = new Vuex.Store({
    state: {
        routes: [],
        sessions: {},
        users: [],
        usersRead:{},
        currentUser: JSON.parse(window.sessionStorage.getItem("user")),
        currentSession: null,
        filterKey: '',
        stomp: null
    },
    getters: {},
    mutations: {
        initRoutes(state, data) {
            state.routes = data
        },
        changeCurrentSession(state, currentSession) {
            if(state.currentSession===null){
                state.currentSession = currentSession
            }
            if(state.usersRead[state.currentUser.username+'#'+currentSession.username]!==0){
                state.usersRead[state.currentUser.username+'#'+currentSession.username] = 0
                putRequest('/chatRecord/'+state.currentSession.id)
            }
            state.currentSession = currentSession;
        },
        addRead(state,msg){
          if (!state.currentUser) {
            state.currentUser = JSON.parse(window.sessionStorage.getItem("user"))
          }
          let mss = state.usersRead[state.currentUser.username + '#' + msg.to]
          if (!mss) {
            Vue.set(state.usersRead, state.currentUser.username + '#' + msg.to, 0)
          }
          if(state.currentSession!==null &&  msg.to!==state.currentSession.username || state.currentSession===null){
              state.usersRead[state.currentUser.username + '#' + msg.to] += 1
          }
        },
        addMessage(state, msg) {
            if (!state.currentUser) {
                state.currentUser = JSON.parse(window.sessionStorage.getItem("user"))
            }
            let mss = state.sessions[state.currentUser.username + '#' + msg.to]
            if (!mss) {
                Vue.set(state.sessions, state.currentUser.username + '#' + msg.to, [])
                // state.sessions[state.currentUser.username+'#'+msg.to] = []
            }
            let date = new Date()
            let month = date.getMonth() + 1
            if (month < 10) {
                month = '0' + month
            }
            let day = date.getDate()
            if (day < 10) {
                day = '0' + day
            }
            state.sessions[state.currentUser.username + '#' + msg.to].push({
                content: msg.content,
                time: date.getFullYear() + '-' + month + '-' + day + ' ' + date.getHours() + ':' + date.getMinutes() + ":" + date.getSeconds(),
                self: !msg.notSelf
            })
        },
        INIT_DATA(state) {
            // let data = localStorage.getItem('vue-chat-session');
            // if (data) {
            //   state.sessions = JSON.parse(data);
            // }
            if (!state.currentUser) {
                state.currentUser = JSON.parse(window.sessionStorage.getItem("user"))
            }
            getRequest('/chatRecord').then(resp => {
                if (resp) {
                    state.sessions = resp.sessions
                    state.usersRead = resp.usersRead
                    getRequest('/chat/users').then(resp => {
                        if (resp) {
                            resp.sort((item1,item2)=>{
                                let tmp2 = state.usersRead[state.currentUser.username+'#'+item2.username]!==undefined ? state.usersRead[state.currentUser.username+'#'+item2.username] : 0
                                let tmp1 = state.usersRead[state.currentUser.username+'#'+item1.username]!==undefined ? state.usersRead[state.currentUser.username+'#'+item1.username] : 0
                                return tmp2-tmp1;
                            })
                            state.users = resp
                        }
                    })

                }
            })
        },
        sort_Users(state) {
            state.users.sort((item1,item2)=>{
                let tmp2 = state.usersRead[state.currentUser.username+'#'+item2.username]!==undefined ? state.usersRead[state.currentUser.username+'#'+item2.username] : 0
                let tmp1 = state.usersRead[state.currentUser.username+'#'+item1.username]!==undefined ? state.usersRead[state.currentUser.username+'#'+item1.username] : 0
                return tmp2-tmp1;
            })
        }
    },
    actions: {
        connect(context) {
            context.state.stomp = Stomp.over(new SockJS('/ws/ep'))
            context.state.stomp.connect({}, success => {
                context.state.stomp.subscribe('/user/queue/chat', msg => {
                    let receivedMsg = JSON.parse(msg.body)
                    receivedMsg.to = receivedMsg.from
                    receivedMsg.notSelf = true
                    context.commit('addMessage', receivedMsg)
                    context.commit('addRead',receivedMsg)
                    context.commit('sort_Users')
                    if (!context.state.currentSession || receivedMsg.from != context.state.currentSession.username) {
                        Notification.info({
                            title: '【' + receivedMsg.fromNickName + '】发来一条消息',
                            message: receivedMsg.content.length > 10 ? receivedMsg.content.substr(0, 10) : receivedMsg.content,
                            duration:0
                        })
                    }
                    // context.state.users.sort()
                })
            }, error => {
                console.log("；连接出错啦")
            })
        },
        initData(context) {
            context.commit('INIT_DATA')
        }
    }
})


store.watch(function (state) {
    return state.sessions
}, function (val) {
    localStorage.setItem('vue-chat-session', JSON.stringify(val));
}, {
    deep: true/*这个貌似是开启watch监测的判断,官方说明也比较模糊*/
})


export default store;